#include "lessonselection.h"
#include "ui_lessonselection.h"
#include <QTreeWidgetItem>
#include <QFileInfo>
#include <QDir>
#include <QMessageBox>
#include <QtDebug>

LessonSelection::LessonSelection(QWidget *parent) :
    QWidget(parent),
    m_ui(new Ui::LessonSelection)
{
    m_ui->setupUi(this);
    scanAndShow("lessons/");
}

void LessonSelection::sendCurrent()
{
    emit selectedLesson(foundLessons.at(m_ui->listWidget->currentRow()));
}

void LessonSelection::updateLesson(Lesson newLesson)
{
    //uggly hack, but founLessons.contains() simply doesn't work, so updating the lessons
    //is tough. might be the Lesson's operator==() fault, but this works for now.
    m_ui->listWidget->clear();
    scanAndShow("lessons/");
}


void LessonSelection::outsideAction(QAction *action)
{
    if (action->text() == "Delete Lesson")
        this->deleteCurrent();

}

void LessonSelection::deleteCurrent()
{
    QListWidgetItem* current = m_ui->listWidget->takeItem(m_ui->listWidget->currentRow());
    QDir dir;
    dir.remove(QString("lessons/").append(current->text()).append(".xml"));

    delete current;
}

void LessonSelection::scanAndShow(QString dirOrFile)
{
    QFileInfo fn;
    fn.setFile(dirOrFile);
    if (fn.isDir())
    {
        QStringList files = QDir(dirOrFile).entryList(QStringList("*.xml"));
        foreach (QString str, files)
            scanAndShow(dirOrFile + str);
        return;
    }

    Lesson temp;
    temp.fromXML(dirOrFile);
    foundLessons.append(temp);
    m_ui->listWidget->addItem(
            new QListWidgetItem(QIcon(QString("icons/")+temp.getIcon()),
                                temp.getName(),
                                m_ui->listWidget));

}

LessonSelection::~LessonSelection()
{
    delete m_ui;
}

void LessonSelection::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
